# -*- coding: utf-8 -*-
"""
简化的系统测试脚本
用于诊断各个模块的导入和基本功能
"""
import sys
import os
import traceback
from datetime import datetime

# 确保项目路径在sys.path中
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

def test_imports():
    """测试模块导入"""
    print(" 测试模块导入...")
    
    test_modules = [
        ('基础算法', 'algorithms.base_algorithm', 'BaseAlgorithm'),
        ('连续追踪器', 'pattern_analysis.consecutive_tracker', 'ConsecutivePatternTracker'),
        ('序列LSTM', 'algorithms.sequence_lstm', 'SequenceAwareLSTM'),
        ('梯度提升', 'algorithms.gradient_boosting', 'GradientBoostingPredictor'),
        ('模式记忆', 'algorithms.pattern_memory', 'PatternMemoryNetwork'),
    ]
    
    results = {}
    
    for name, module_path, class_name in test_modules:
        try:
            module = __import__(module_path, fromlist=[class_name])
            cls = getattr(module, class_name)
            results[name] = {'status': '✅ 成功', 'class': cls}
            print(f"  ✅ {name:15} - 导入成功")
        except Exception as e:
            results[name] = {'status': '❌ 失败', 'error': str(e)}
            print(f"  ❌ {name:15} - 导入失败: {e}")
    
    return results

def test_basic_functionality():
    """测试基本功能"""
    print("\n🧪 测试基本功能...")
    
    try:
        # 测试连续追踪器
        from pattern_analysis.consecutive_tracker import ConsecutivePatternTracker
        
        tracker = ConsecutivePatternTracker('ssq')
        print("  ✅ 连续追踪器创建成功")
        
        # 创建模拟数据
        mock_data = []
        for i in range(10):
            period = [1+i, 2+i, 3+i, 4+i, 5+i, 6+i, 16]  # 模拟双色球数据
            mock_data.append(period)
        
        # 测试模式分析
        patterns = tracker.analyze_consecutive_patterns(create_mock_dataframe(mock_data))
        print(f"  ✅ 模式分析完成，发现 {len(patterns.get('consecutive_patterns', {}))} 个模式")
        
    except Exception as e:
        print(f"  ❌ 基本功能测试失败: {e}")
        traceback.print_exc()

def create_mock_dataframe(data):
    """创建模拟的DataFrame"""
    try:
        import pandas as pd
        
        columns = ['Red_1', 'Red_2', 'Red_3', 'Red_4', 'Red_5', 'Red_6', 'Blue_1']
        df = pd.DataFrame(data, columns=columns)
        return df
    except ImportError:
        print("警告：pandas未安装，使用简化的数据结构")
        # 返回简化的数据结构
        return {
            'data': data,
            'columns': ['Red_1', 'Red_2', 'Red_3', 'Red_4', 'Red_5', 'Red_6', 'Blue_1']
        }

def test_algorithm_creation():
    """测试算法实例化"""
    print("\n🤖 测试算法实例化...")
    
    algorithms = {}
    
    # 测试序列LSTM
    try:
        from algorithms.sequence_lstm import SequenceAwareLSTM
        lstm_algo = SequenceAwareLSTM(input_dim=7, hidden_dim=32, output_dim=33)
        algorithms['LSTM'] = lstm_algo
        print("  ✅ 序列LSTM创建成功")
    except Exception as e:
        print(f"  ❌ 序列LSTM创建失败: {e}")
    
    # 测试梯度提升
    try:
        from algorithms.gradient_boosting import GradientBoostingPredictor
        gb_algo = GradientBoostingPredictor('ssq')
        algorithms['GradientBoosting'] = gb_algo
        print("  ✅ 梯度提升创建成功")
    except Exception as e:
        print(f"  ❌ 梯度提升创建失败: {e}")
    
    # 测试模式记忆
    try:
        from algorithms.pattern_memory import PatternMemoryNetwork
        pm_algo = PatternMemoryNetwork('ssq', memory_size=100)
        algorithms['PatternMemory'] = pm_algo
        print("  ✅ 模式记忆创建成功")
    except Exception as e:
        print(f"  ❌ 模式记忆创建失败: {e}")
    
    return algorithms

def test_simple_prediction():
    """测试简单预测"""
    print("\n🎯 测试简单预测...")
    
    try:
        algorithms = test_algorithm_creation()
        
        if not algorithms:
            print("  ❌ 没有可用的算法进行测试")
            return
        
        # 创建模拟的输入数据
        import numpy as np
        mock_recent_data = np.random.randn(5, 7)  # 5期，7个特征
        mock_historical_data = []
        
        for i in range(20):
            period = [np.random.randint(1, 34) for _ in range(6)] + [np.random.randint(1, 17)]
            mock_historical_data.append(period)
        
        for name, algorithm in algorithms.items():
            try:
                print(f"  🔍 测试 {name} 预测...")
                
                # 训练
                algorithm.train(mock_historical_data)
                
                # 预测
                if hasattr(algorithm, 'predict_multiple_sets'):
                    predictions = algorithm.predict_multiple_sets(mock_recent_data, {}, num_sets=1)
                elif hasattr(algorithm, 'predict'):
                    predictions = algorithm.predict(mock_recent_data, num_predictions=1)
                else:
                    print(f"    ⚠️ {name} 缺少预测方法")
                    continue
                
                print(f"    ✅ {name} 预测成功：{len(predictions)}组")
                
                # 显示预测结果示例
                if predictions and len(predictions) > 0:
                    pred = predictions[0]
                    if isinstance(pred, dict):
                        red = pred.get('red', pred.get('red_balls', []))
                        blue = pred.get('blue', pred.get('blue_balls', []))
                        print(f"      示例：红球{red}，蓝球{blue}")
                    else:
                        print(f"      示例：{pred}")
                        
            except Exception as e:
                print(f"    ❌ {name} 预测失败: {e}")
    
    except Exception as e:
        print(f"  ❌ 预测测试整体失败: {e}")
        traceback.print_exc()

def main():
    """主测试函数"""
    print("🎰 LottoProphet 多算法系统 - 诊断测试")
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Python版本: {sys.version}")
    print("=" * 60)
    
    # 导入测试
    import_results = test_imports()
    
    # 基础功能测试
    if any(r['status'] == '✅ 成功' for r in import_results.values()):
        test_basic_functionality()
        test_simple_prediction()
    else:
        print(" 所有模块导入失败，跳过功能测试")
    
    # 结果总结
    print("\n" + "=" * 60)
    successful_imports = [name for name, result in import_results.items() 
                         if result['status'] == '✅ 成功']
    
    print(f" 测试总结:")
    print(f"  成功导入模块: {len(successful_imports)}/{len(import_results)}")
    
    if successful_imports:
        print(f"  ✅ 可用模块: {', '.join(successful_imports)}")
        if len(successful_imports) >= 3:
            print("🎉 系统基本可用！")
        else:
            print("⚠️ 需要修复更多模块")
    else:
        print(" 系统不可用，需要修复所有导入问题")
    
    print("\n🏁 诊断测试完成！")

if __name__ == "__main__":
    main()